package com.jarvanmo.ImageEditor;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import me.kareluo.imaging.IMGEditActivity;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * This class echoes a string called from JavaScript.
 */
public class ImageEditor extends CordovaPlugin {

    private CallbackContext callbackContext;
    private String storedFilePath;
    private int requestCodeEditImage  = 1111;
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("imageEditor")) {
            String message = args.getString(0);
            this.parseMessage(message, callbackContext);
            return true;
        }
        return false;
    }

    private void parseMessage(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) {
            this.callbackContext = callbackContext;
            cordova.setActivityResultCallback(this);
           String filePath =   getRealFilePath(message);
           openImageEditor(filePath);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }

    private String getRealFilePath(String filePath){
        if(filePath.startsWith("content://")){
            File file = getFileFromContentProvider(filePath);
            if (file != null) {
                return file.getAbsolutePath();
            }else {
                return null;
            }
        }else {
            return  filePath;
        }
    }

    private  File getFileFromContentProvider(String path) {
        Source source = null;
        BufferedSink sink = null;

        File file = null;
        try {
            Context context = cordova.getActivity().getApplicationContext();
            Uri uri = Uri.parse(path);
            String suffix = null;
            String mimeType = context.getContentResolver().getType(uri);
            if (TextUtils.equals(mimeType, "image/jpeg") || TextUtils.equals(mimeType, "image/jpg")) {
                suffix = ".jpg";
            } else if (TextUtils.equals(mimeType, "image/png")) {
                suffix = ".png";
            }


            file = File.createTempFile(UUID.randomUUID().toString(), suffix);
            InputStream inputStream = context.getContentResolver().openInputStream(uri);

            if (inputStream == null) {
                return null;
            }
            
            OutputStream outputStream = new FileOutputStream(file);
            sink = Okio.buffer(Okio.sink(outputStream));
            source = Okio.source(inputStream);
            sink.writeAll(source);
            source.close();
            sink.close();
        } catch (IOException e) {
          e.printStackTrace();
        }

        return file;
    }

    private void openImageEditor(String path){

        try {
            File file = File.createTempFile(UUID.randomUUID().toString(),".jpg");
            storedFilePath = file.getAbsolutePath();
            Intent intent = new Intent(cordova.getActivity(),IMGEditActivity.class);
            Uri uri = Uri.fromFile(new File(path));
            intent.putExtra(IMGEditActivity.EXTRA_IMAGE_URI,uri);
            intent.putExtra(IMGEditActivity.EXTRA_IMAGE_SAVE_PATH,storedFilePath);
            cordova.getActivity().startActivityForResult(intent,requestCodeEditImage);
        } catch (IOException e) {
           if(callbackContext != null){
               callbackContext.error(e.getMessage());
               callbackContext = null;
           }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if(requestCode  == requestCodeEditImage ){
            if (callbackContext == null) {
                return;
            }
            if(resultCode == Activity.RESULT_OK ){
                callbackContext.success(storedFilePath);
                callbackContext = null;
            }else {
                callbackContext.error("canceled");
                callbackContext = null;
            }
        }
    }
}
